/*
 * @Author: LVGRAPE
 * @LastEditors: LVGRAPE
 */

/***
 * @Author: LVGRAPE
 * @Date: 2022-11-10 10:05:53
 * @LastEditTime: 2023-11-10 00:51:20
 * @LastEditors: LVGRAPE
 * @Description:
 * @FilePath: \ZINO_MCU_SOURCE\ZINO_SRC\i2c_dev.h
 * @可以输入预定的版权声明、个性签名、空行等
 */

#ifndef __SOTF_I2C_H_
#define __SOTF_I2C_H_
#ifdef __cplusplus
extern "C"
{
#endif // __cplusplus

#include <stdint.h>
#include "zino_pin.h"

#define CRC_MAGICBEE 0XED


    typedef struct
    {
        zino_io_t *sda;
        zino_io_t *scl;
        uint8_t slave_addr;
        uint32_t delay_us;
        struct zino_soft_i2c_ops *ops;
    } zino_soft_i2c_bus_t;
    struct zino_soft_i2c_ops{
        uint8_t (*start)(zino_soft_i2c_bus_t *bus);
        void (*stop)(zino_soft_i2c_bus_t *bus);
        void (*sendByte)(zino_soft_i2c_bus_t *bus, uint8_t byte);
        uint8_t (*readByte)(zino_soft_i2c_bus_t *bus);
        uint8_t (*readAck)(zino_soft_i2c_bus_t *bus);
        void (*sendAck)(zino_soft_i2c_bus_t *bus, uint8_t ack);
        uint8_t (*scan)(zino_soft_i2c_bus_t *bus, uint8_t *buff);
        uint8_t (*write)(zino_soft_i2c_bus_t *bus, uint8_t regaddr, uint8_t *buff, uint8_t len);
        uint8_t (*read)(zino_soft_i2c_bus_t *bus, uint8_t regaddr, uint8_t *buff, uint8_t len);
    };
    void zino_soft_i2c_init(zino_soft_i2c_bus_t *bus, zino_io_t *scl, zino_io_t *sda, uint8_t slave_addr, uint32_t delayUs);
    // inline void zino_i2c_dev_register(zino_soft_i2c_bus_t *dev)
    // {
    //     dev->write = soft_i2c_write;
    //     dev->read = soft_i2c_read;
    //     // todo 加链表来保存指针头，或者指定flash地址保存函数
    // };
    // inline void zino_i2c_dev_register_withAddr(soft_i2c_dev_t *dev, uint8_t addr)
    // {
    //     dev->setAddress = addr;
    //     dev->write = soft_i2c_write;
    //     dev->read = soft_i2c_read;
    //     // todo 加链表来保存指针头，或者指定flash地址保存函数
    // };
    // void zino_i2c_dev_getInfo(zino_i2c_dev_t *dev);
    // void zino_i2c_dev_setAddress(zino_i2c_dev_t *dev, uint16_t newAddr);
    /** FIXME 硬件暂时做不了16位地址
     * 1.ZINO I2C统一使用16位I2C从机地址，最低位为读写标志
     * 2.ZINO I2C都支持双从机地址，固定地址为0x0102且不可更改，第二地址可以自定义，范围0x0000~0xffff,
     * 最低位为读写标志，为避免和市场上的7位地址器件重复，最好要从0x0104开始用，实际可以用也有30000多个
     *
     */
    typedef struct
    {
        // uint8_t type;
        uint8_t size;
        uint8_t *buffer;
        uint8_t crc;
    } zino_i2c_msg_t;
    void i2c_msg_crc_cal(zino_i2c_msg_t *msg);
    uint8_t i2c_txbuff_crc_cal(uint8_t *buff, uint8_t size);
#ifdef __cplusplus
}
#endif // __cplusplus
#endif
